﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Threading;
using System.IO;

namespace Valgmaskine_Website
{
    public partial class _default : System.Web.UI.Page
    {
        const string _conString = @"Data Source=msdb3.surftown.dk;Initial Catalog=mitoden_dbgr20;User ID=mitoden_dbgr20;Password=dmgruppebjbu";
        SqlConnection con = new SqlConnection(_conString);

        ServiceRef.Service1Client Serve = new ServiceRef.Service1Client();

        

        protected void Page_Load(object sender, EventArgs e) //Page_Load køres hver gang default.aspx loades,
        {
            if (Session["loggedPå"] == null)
            {
                Response.Redirect("/login/");
            }
            else
            {
                Serve.UpdateWebsiteFromDB();
            }
            
        }

        public string GetValgsted()
        {
            txtMsg.Text = "";
            
            try
            {
                string str = "";
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                foreach (int i in Serve.ReturnValgsted())
                {
                    cmd.CommandText = "SELECT aAdresse FROM Afstemningssted WHERE aId = '" + i + "'";
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        str += reader["aAdresse"] + "\r\n \r\n";
                    }
                    reader.Close();
                }
                
                return str;
            }
            catch (SqlException e)
            {
                throw e;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
        }

        protected void BtnGo_Click(object sender, EventArgs e)
        {
            int i = 0;
            //string[] splitstr = GetValgsted().Split('#');
            //foreach (string s in splitstr)
            //{
            //    if (i == 3)
            //    {
            //        txtMsg.Text += "\r\n" + s + "\r\n";
            //        i = 0;
            //    }
            //    else
            //    {
            //        txtMsg.Text += s + "\r";
            //    }
                
            //    i++;
            //}

            string streng = GetValgsted();


            txtMsg.Text += streng.Replace("#", "\r\n");

            if (i == 3)
            {
                txtMsg.Text += "\r\n \r\n";
                i = 0;
            }

            i++;
        }
    }
}